'''
### Adapted from collective.flowplayer event subscibers
'''

from Products.Archetypes.interfaces import IObjectInitializedEvent
from Products.CMFPlone.utils import getToolByName
from Products.CMFPlacefulWorkflow.PlacefulWorkflowTool import \
                                                WorkflowPolicyConfig_id

import logging
from StringIO import StringIO

VIDEO_EXTENSIONS = ['.f4b', '.f4p', '.f4v', '.flv', '.mp4', '.m4v', '.mov']

WORKSPACE_POLICY_ID = 'apkn_workspace_placeful_policy'

class ChangeDefaultView(object):
    '''
    This might be unecessary since collective.flowplayer sets the
    views accordingly
    '''
    def __init__(self, object, event):
        self.object = object
        self.content = content = event.object

        ext = self.check_extension()
        if ext is None:
            self.content.setLayout(self.content.default_view)
            return
        if IObjectInitializedEvent.providedBy(event):
            self.content.setLayout('flowplayer')

    def check_extension(self):
        for ext in VIDEO_EXTENSIONS:
            if self.content.getFilename().endswith(ext):
                return ext
        return None


class SetWorkflowPolicy(object):
    '''
    Set the workflow policy for workspace folders
    '''
        
    def __init__(self, object, event):
        self.object = object
        
        if IObjectInitializedEvent.providedBy(event):
            self.set_workflow_policy()

    @property
    def placeful_workflow_tool(self):
        return getToolByName(self.object, 'portal_placeful_workflow', None)

    def set_workflow_policy(self):
        if self.placeful_workflow_tool is None:
            logging.error('Unable to acquire placeful workflow tool. Check your Plone setup')
            return
        else:
            self.object.manage_addProduct['CMFPlacefulWorkflow'].\
                                        manage_addWorkflowPolicyConfig()
            wfp = getattr(self.object, WorkflowPolicyConfig_id)
            wfp.setPolicyIn(WORKSPACE_POLICY_ID)
            wfp.setPolicyBelow(WORKSPACE_POLICY_ID)
            logging.info('Finished configuring %s workflow policy',
            self.object.getId())
        return
